package com.qinglei.recoup.system.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qinglei.recoup.common.domain.CommonRes;
import com.qinglei.recoup.system.domain.*;
import com.qinglei.recoup.system.pojo.AddBuildingParam;
import com.qinglei.recoup.system.pojo.BuildingShowVO;
import com.qinglei.recoup.system.pojo.TimePeriodParam;
import com.qinglei.recoup.system.pojo.PageParam;
import com.qinglei.recoup.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author zxy
 */
@Api(tags = "楼 相关控制器-张-已实现")
@RestController
@RequestMapping("/building")
public class BuildingController {

    @Autowired
    private BuildingService buildingService;

    @Autowired
    private BedService bedService;

    @Autowired
    private RadarBedService radarBedService;

    @Autowired
    private FloorService floorService;

    @Autowired
    private RoomService roomService;

    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    private MonitorTimeService monitorTimeService;

    @ApiOperation(value = "分页查询楼")
    @GetMapping("/showPage")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页码，从1开始，默认是1", paramType = "query", dataType = "Integer", required = false),
            @ApiImplicitParam(name = "pageSize", value = "每页条数，默认20", paramType = "query", dataType = "Integer")
    })
    public CommonRes<IPage<BuildingShowVO>> showPageBuilding(PageParam pageParam) {
        return buildingService.showPageBuilding(pageParam);
    }

    @ApiOperation(value = "添加楼")
    @PostMapping
    @ApiImplicitParam(name = "name", value = "楼名称", paramType = "body", dataType = "String")
    public CommonRes addBuilding(@RequestBody AddBuildingParam addBuildingParam) {
        Integer integer = buildingService.getBaseMapper().selectCount(Wrappers.<Building>lambdaQuery().eq(Building::getName, addBuildingParam.getName()));
        if (integer > 0){
            return CommonRes.failed("楼名称重复");
        }
        Building building = new Building();
        BeanUtils.copyProperties(addBuildingParam,building);
        building.setOutBedTimeoutUnified(1);
        building.setMonitorTimeUnified(1);
        //默认离床时间阀值
        String outBedTimeout = systemConfigService.getDefaultOutBedTimeout();
        building.setOutBedTimeout(outBedTimeout);
        int count = buildingService.getBaseMapper().insert(building);
        //默认监控时间
        List<TimePeriodParam> monitorTimeList = systemConfigService.getDefaultMonitorTime();
        for (TimePeriodParam sc:monitorTimeList) {
            MonitorTime monitorTime = new MonitorTime();
            monitorTime.setStartTime(sc.getStartTime());
            monitorTime.setEndTime(sc.getEndTime());
            monitorTime.setObjId(building.getId());
            monitorTime.setType(SystemConfigService.TYPE_TAKE_EVENT_TIMEOUT);
            monitorTimeService.getBaseMapper().insert(monitorTime);
        }
        if (count>0){
            return CommonRes.ok();
        }
        return CommonRes.failed("新增楼失败");
    }

    @ApiOperation(value = "通过楼id查询楼")
    @GetMapping("/{id}")
    @ApiImplicitParam(name = "id", value = "楼id", paramType = "path", dataType = "Integer")
    public CommonRes<BuildingShowVO> getBuildingById(@PathVariable Integer id) {
        Building building = buildingService.getBaseMapper().selectById(id);
        BuildingShowVO buildingShowVO = new BuildingShowVO();
        BeanUtils.copyProperties(building,buildingShowVO);
        return CommonRes.ok(buildingShowVO);
    }

    @ApiOperation(value = "修改楼信息")
    @PutMapping
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "楼id", paramType = "body", dataType = "Integer",required = true),
            @ApiImplicitParam(name = "name", value = "楼名称", paramType = "body", dataType = "String",required = true)})
    public CommonRes updateBuilding(@RequestBody BuildingShowVO buildingShowVO) {
        Integer integer = buildingService.getBaseMapper().selectCount(Wrappers.<Building>lambdaQuery()
                .eq(Building::getName, buildingShowVO.getName()).last("and id != "+buildingShowVO.getId()));
        if (integer > 0){
            return CommonRes.failed("楼名称重复");
        }
        Building building = new Building();
        BeanUtils.copyProperties(buildingShowVO,building);
        int count = buildingService.getBaseMapper().updateById(building);
        if (count > 0){
            return CommonRes.ok();
        }
        return CommonRes.failed("修改楼信息失败");
    }

    @ApiOperation(value = "通过楼id删除楼")
    @DeleteMapping("/{id}")
    @Transactional(rollbackFor = Exception.class)
    @ApiImplicitParam(name = "id", value = "楼id", paramType = "path", dataType = "Integer",required = true)
    public CommonRes delBuildingById(@PathVariable Integer id) {
        List<Bed> beds = bedService.getBaseMapper().selectList(Wrappers.<Bed>lambdaQuery().eq(Bed::getBuildingId, id));
        for (Bed b:beds) {
            Integer bedCount = radarBedService.getBaseMapper().selectCount(Wrappers.<RadarBed>lambdaQuery().eq(RadarBed::getBedId, b.getId()));
            if (bedCount > 0) {
                return CommonRes.failed("该楼已有床位绑定监测仪，不能删除，如果想删除，请先解绑监测仪");
            }
        }
        int count = buildingService.getBaseMapper().deleteById(id);
        if (count > 0){
            List<Floor> floors = floorService.getBaseMapper().selectList(Wrappers.<Floor>lambdaQuery().eq(Floor::getBuildingId, id));
            for (Floor f:floors) {
                roomService.getBaseMapper().delete(Wrappers.<Room>lambdaUpdate().eq(Room::getFloorId,f.getId()));
            }
            floorService.getBaseMapper().delete(Wrappers.<Floor>lambdaUpdate().eq(Floor::getBuildingId,id));
            bedService.getBaseMapper().delete(Wrappers.<Bed>lambdaUpdate().eq(Bed::getBuildingId,id));
            return CommonRes.ok();
        }
        return CommonRes.failed("删除楼信息失败");
    }



    @ApiOperation(value = "添加一个楼床位数量")
    @PutMapping("/add/{id}")
    @ApiImplicitParam(name = "id", value = "楼id", paramType = "path", dataType = "Integer",required = true)
    public CommonRes addBedCnt(@PathVariable Integer id) {
        return buildingService.addBedCnt(id);

    }


    @ApiOperation(value = "减少一个楼床位数量")
    @PutMapping("/sub/{id}")
    @ApiImplicitParam(name = "id", value = "楼id", paramType = "path", dataType = "Integer",required = true)
    public CommonRes subBedCnt(@PathVariable Integer id) {
        return buildingService.subBedCnt(id, 1);
    }


    @ApiOperation(value = "查询楼")
    @GetMapping("/allBuilding")
    public CommonRes allBuilding() {
        List<Building> buildings = buildingService.getBaseMapper().selectList(Wrappers.emptyWrapper());
        Building building = new Building();
        building.setName("全部");
        buildings.add(0,building);
        return CommonRes.ok(buildings);
    }

    @ApiOperation(value = "查询当前院长下的楼")
    @GetMapping("/allDeanBuilding")
    public CommonRes allDeanBuilding() {
        List<Building> buildings = buildingService.allDeanBuilding();
        Building building = new Building();
        building.setName("全部");
        buildings.add(0,building);
        return CommonRes.ok(buildings);
    }
}
